<template>
  <el-form ref="ruleFormRef" size="large" :model="form" :rules="rules">
    <el-form-item prop="name">
      <el-input
        v-model="form.name"
        clearable
        placeholder="请输入邮箱/已验证手机号"
      />
    </el-form-item>
    <el-form-item prop="validCode">
      <el-input v-model="form.validCode" placeholder="请输入验证码" clearable>
        <template #append>
          <el-button :disabled="sendModel.disabled" @click="getCode">
            {{ sendModel.content }}
          </el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" class="w-full" @click="submitForm">
        登录
      </el-button>
    </el-form-item>
  </el-form>
  <el-dialog title="提示" v-model="dialog.visible" width="500px">
    <el-form ref="pwdFormRef" size="large" :model="form" :rules="rules">
      <el-form-item prop="captchaCode">
        <el-input
          v-model="form.captchaCode"
          auto-complete="off"
          :placeholder="$t('login.captchaCode')"
          class="w-[60%]"
        />
        <div class="h-[40px]">
          <el-image
            :src="captchaBase64"
            @click="getCaptcha"
            class="w-[130px] h-[40px] cursor-pointer"
          >
            <template #error>
              <div class="image-slot">
                <i-ep-picture />
              </div>
            </template>
          </el-image>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialog.visible = false">
          {{ $t("common.cancel") }}
        </el-button>
        <el-button type="primary" @click="getSendcode">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { vueMetaEnv } from "@/settings";
import type { FormInstance, FormRules } from "element-plus";
import { reactive, ref } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { getCaptchaApi, sendcode, logincode } from "@/api/auth";
import type { SendModelRef, VerificateRef } from "@/api/auth/types";
import type { DialogRef } from "@/types/index";
const captchaBase64 = ref(); // 验证码图片Base64字符串
const dialog = reactive<DialogRef>({
  title: "",
  visible: false,
});
const sendModel: SendModelRef = reactive({
  content: "获取验证码",
  timers: 60,
  disabled: false,
});
const form: VerificateRef = reactive({
  name: "",
  captchaId: "",
  captchaCode: "",
  validCode: "",
});

const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules<VerificateRef>>({
  captchaCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  name: [{ required: true, message: "请输入邮箱或手机号", trigger: "blur" }],
  // validCode: [
  //   { required: true, message: "请输入6位数字的验证码", trigger: "blur" },
  // ],
});

/**
 * 获取验证码
 */
function getCaptcha() {
  getCaptchaApi().then(({ data }) => {
    form.captchaId = data.captchaId;
    captchaBase64.value = data.base64Image;
    dialog.visible = true;
    form.captchaCode = "";
  });
}

function getCode() {
  getCaptcha();
}

// 发送验证码
const getSendcode = async () => {
  await ruleFormRef.value?.validate((valid) => {
    if (valid) {
      // 关闭验证码弹框
      dialog.visible = false;
      // 发送验证码
      const formData = {
        tenant: useUserStore().user.tenant,
        name: form.name,
        captchaId: form.captchaId,
        captchaCode: form.captchaCode,
        sendValidCode: true,
        directoryId: vueMetaEnv.APP_DIRECTORY_ID as string,
        product: vueMetaEnv.APP_PRODUCT as string,
      };
      sendcode(formData).then(({ data }) => {
        console.log(data);
        const timer = window.setInterval(() => {
          sendModel.content = sendModel.timers + "s后重新发送";
          sendModel.timers--;
          sendModel.disabled = true;
          if (sendModel.timers < 0) {
            sendModel.timers = 60;
            sendModel.disabled = false;
            sendModel.content = "重新发送验证码";
            window.clearInterval(timer);
          }
        }, 1000);
      });
    }
  });
};

// 提交表单校验
function submitForm() {
  const formData = {
    tenant: useUserStore().user.tenant,
    directoryId: "jmash",
    name: form.name,
    validCode: form.validCode,
    clientId: vueMetaEnv.APP_CLIENT_ID,
    scope: "",
  };
  logincode(formData).then((response) => {
    console.log(response);
  });
}
</script>
